package les.projeto;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class TeachersView extends Activity{
	
	private String teachersName = "";
	private String teachersSite = "";
	private String teachersCourses = "";
	private String[][] aboutTeachers = null;
	
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.teachers);
	    
	    updateListValues();
	    ListView teachers = (ListView)findViewById(R.id.listViewTeachers);
	    teachers.setOnItemClickListener(new OnItemClickListener() {
	    	@Override
	    	public void onItemClick(AdapterView<?> parent, View view,
	    		int position, long id) {
	    		showTeacher(aboutTeachers[position][0], aboutTeachers[position][1],
		    					aboutTeachers[position][2]);
	    	}
	    });
}
	
	private void updateListValues() {
	    ListView teachers = (ListView)findViewById(R.id.listViewTeachers);

	    BD bd = new BD();
	    ArrayList<String> profs = bd.getTeachers(this);
	    
		aboutTeachers = new String[profs.size()][3];
	    
	    for (int i = 0; i < profs.size(); i++) {
			String[] date = profs.get(i).split(" ");
			aboutTeachers[i][0] = date[0];
			aboutTeachers[i][1] = date[1];
			aboutTeachers[i][2] = date[2];
		}
	    
	    String[] values = new String[aboutTeachers.length];
	    for (int i = 0; i < values.length; i++) {
			values[i] = aboutTeachers[i][0].replace(".", " ");
		}
	    
	    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
	    		android.R.layout.simple_list_item_1, android.R.id.text1, values);
	    teachers.setAdapter(adapter);
	    teachers.invalidate();
	}

	private void showTeacher(final String name, final String site, final String courses) {
	    BD bd = new BD();
	    ArrayList<String> aux = bd.getSubjectsByTeacher(this, name);
	    	    
        String coursesAux = courses.replace(".", "; ");
        if (!(coursesAux.endsWith(";")))
            coursesAux = coursesAux +"; ";
        

        if (coursesAux.contains("Any"))
            coursesAux = "";
            
	    for (int i = 0; i < aux.size(); i++) {
            String date[] = aux.get(i).split(" ");
            if (!(coursesAux.contains(date[0])))
                coursesAux = coursesAux + date[0] +"; ";
        }
	    
		 final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 String nameAux = name.replace(".", " ");
		 helpBuilder.setTitle(nameAux);
		 helpBuilder.setMessage("Site: " + site + "\nDisciplines: " + coursesAux);
		 helpBuilder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  editTeacherName(name, site, courses);
				  dialog.cancel();
			  }
		 });
		 helpBuilder.setNegativeButton("back", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  dialog.cancel();
			  }
			 });
		 helpBuilder.setNeutralButton("remove", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  BD bd = new BD();
				  bd.removeTeacher(TeachersView.this, name);
				  dialog.cancel();
				  startActivity(getIntent()); 
				  finish();
			  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
		}
	
	protected void editTeacherSite(final String name, String site, final String courses) {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Editing teacher" + name);
		 helpBuilder.setMessage("Enter the new site of the teacher: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText(site);
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  teachersSite = "";
				  teachersSite = input.getText().toString();
                  if (teachersSite.isEmpty())
                      teachersSite = "Any";
                  else{
                      String[] sites = teachersSite.split(" ");
                      teachersSite = sites[0];
                  }
				  dialog.cancel();
				  editTeacherCourses(name, courses);
			  }
		 });
		 helpBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
		
	}

	protected void editTeacherCourses(final String name, String courses) {
	       AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
	         helpBuilder.setTitle("Select a discipline");
	            
	        teachersCourses = "";
	        
	        final BD bd = new BD();
	        ArrayList<String> subjects = bd.getSubjects(this);
	           if (subjects.isEmpty())
	                subjects.add("Any - -");
	        String[][] subjectsAux = new String[subjects.size()][3];
	        
	        final String [] bdSubjects = new String[subjectsAux.length];
	        for (int i = 0; i < subjects.size(); i++) {
	            String[] date = subjects.get(i).split(" ");
	            bdSubjects[i] = date[0];
	            
	        }
	        
	        boolean[] _selections =  new boolean[bdSubjects.length];
	        helpBuilder.setMultiChoiceItems(bdSubjects, _selections, new DialogInterface.OnMultiChoiceClickListener() {
	            
	            @Override
	            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
	                SparseBooleanArray CheCked = ((AlertDialog)dialog).getListView().getCheckedItemPositions();
	                teachersCourses = "";
	                for (int i = 0; i < CheCked.size(); i++) {
	                    if (CheCked.get(CheCked.keyAt(0))){
	                        teachersCourses =  teachersCourses + bdSubjects[i] + ".";
	                    }
	                }
	            }
	        });
	            
	         helpBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
	              @Override
	              public void onClick(DialogInterface dialog, int which) {
	                  if ( teachersCourses.isEmpty())
	                      teachersCourses = "Any";
	                  dialog.cancel();
	                  bd.editTeacher(TeachersView.this, name,teachersName, teachersSite, teachersCourses);
	                  updateListValues();
	                  dialog.cancel();
	              }
	         });
		 helpBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();		
	}
	
	protected void editTeacherName(final String name, final String site, final String courses) {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Editing teacher " + name);
		 helpBuilder.setMessage("Enter the new name of the teacher: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText(name);
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  teachersName = "";
				  teachersName = input.getText().toString();
                  teachersName = teachersName.replace(" ", ".");
				  editTeacherSite(name, site, courses);
				  dialog.cancel();
			  }
		 });
		 helpBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();		
	}

	private void addNameTeacher() {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Add Teacher");
		 helpBuilder.setMessage("Enter the name of the teacher: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText("");
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  teachersName = "";				  
				  teachersName = input.getText().toString();
				  teachersName = teachersName.replace(" ", ".");
				  dialog.cancel();
				  addSiteTeacher();
			  }
		 });
		 helpBuilder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
	}

	protected void addSiteTeacher() {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Add Teacher");
		 helpBuilder.setMessage("Enter the site of the teacher: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText("");
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  teachersSite = "";
				  teachersSite = input.getText().toString();
				  if (teachersSite.isEmpty())
				      teachersSite = "Any";
				  else{
				      String[] sites = teachersSite.split(" ");
	                  teachersSite = sites[0];
				  }
				  dialog.cancel();
				  addCoursesTeacher();
			  }
		 });
		 helpBuilder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
		
	}

	protected void addCoursesTeacher() {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Select a discipline");
	        
        teachersCourses = "";
        
        BD bd = new BD();
        ArrayList<String> subjects = bd.getSubjects(this);
           if (subjects.isEmpty())
                subjects.add("Nenhum - -");
        String[][] subjectsAux = new String[subjects.size()][3];
        
        final String [] bdSubjects = new String[subjectsAux.length];
        for (int i = 0; i < subjects.size(); i++) {
            String[] date = subjects.get(i).split(" ");
            bdSubjects[i] = date[0];
            
        }
        
        boolean[] _selections =  new boolean[ bdSubjects.length ];
        helpBuilder.setMultiChoiceItems(bdSubjects, _selections, new DialogInterface.OnMultiChoiceClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                SparseBooleanArray CheCked = ((AlertDialog)dialog).getListView().getCheckedItemPositions();
                teachersCourses = "";
                for (int i = 0; i < CheCked.size(); i++) {
                    if (CheCked.get(CheCked.keyAt(0))){
                        teachersCourses =  teachersCourses + bdSubjects[i] + ".";
                    }
                }
            }
        });
	        
		 helpBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
			      if ( teachersCourses.isEmpty())
			          teachersCourses = "Any";
			      dialog.cancel();
                  addTeacherInBD();
			  }
		 });
		 helpBuilder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
	}

	protected void addTeacherInBD() {
	    BD bd = new BD();
	    bd.insertTeacher(this, teachersName, teachersSite, teachersCourses);
	    startActivity(getIntent()); 
	    finish();
	}
	
	@Override
	public void onBackPressed() {
		
        back();	        		 
        return;
	}

	private void back() {
		Calendar date = Calendar.getInstance();
		int month = date.get(Calendar.MONTH);
        int year = date.get(Calendar.YEAR);
        int today = date.get(Calendar.DAY_OF_MONTH);
        
	    Intent trocatela = new Intent(TeachersView.this, CalendarView.class);
		trocatela.putExtra("date", year+"-"+month+"-"+today);

		TeachersView.this.startActivity(trocatela);
		TeachersView.this.finish();
	}

    private void addTeacher() {
        addNameTeacher();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     super.onCreateOptionsMenu(menu);
     menu.add(0,0,0,"Add Teacher");
     return true;
    } 
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
     super.onOptionsItemSelected(item);
     switch (item.getItemId()) {
        case 0:
            addTeacher();
            break;
     }
     return false;
    } 
}
